export const usePermissionPinia = defineStore('permission', () => {
  const dialogView = ref<any>(null)
  const permissionListener = ref<any>(null)
  const tips = ref<any[]>([
    {
      name: 'READ_CALENDAR',
      title: '手机状态权限申请说明',
      content: '正在申请手机日历日历状态权限，允许或拒绝均不会获取任何隐私信息。',
    },
    {
      name: 'CALL_PHONE',
      title: '拨打电话权限申请说明',
      content: '应用正在申请拨打电话权限，用于联系客服等功能，允许或拒绝不会获取任何隐私信息。',
    },
    {
      name: 'CAMERA',
      title: '摄像头权限申请说明',
      content: '应用需要申请摄像头权限，用于更换图像等功能时候拍照上传图片。',
    },
    {
      name: 'READ_EXTERNAL_STORAGE',
      title: '读取存储权限申请说明',
      content: '正在申请读取存储权限,访问设备上的照片、媒体内容和文件，允许或拒绝均不会获取任何隐私信息。',
    },
    {
      name: 'WRITE_EXTERNAL_STORAGE',
      title: '相机/相册权限说明',
      content: '应用需要读取相册权限，用于在更换图像时上传图片。',
    },
    {
      name: 'ACCESS_FINE_LOCATION',
      title: '位置信息权限使用说明',
      content: '用于获取用户当前位置，并提供所在区域的服务。',
    },
    {
      name: 'ACCESS_BACKGROUND_LOCATION',
      title: '位置信息权限使用说明',
      content: '用于获取用户当前位置，并提供所在区域的服务。',
    },
    {
      name: 'RECORD_AUDIO',
      title: '麦克风权限使用说明',
      content: '用于获取用户麦克风权限，并开启应用录音功能。允许或拒绝不会获取任何隐私信息。',
    },
  ])

  // 监听权限申请
  async function requstPermission(permissionID) {
    return new Promise((resolve, reject) => {
      try {
        // if (!uni.getSystemInfoSync().platform == 'android') return resolve(true)
        /**
         * &#64;description plus.navigator.checkPermission 检查应用是否获取指定权限
         * 有些权限检测不到 就继续下面的代码&#xff0c;比如相册权限就可以直接检测&#xff0c;就很方便&#xff0c;授权情况下不需要再走下面代码了
         * checkPermission 返回参数
         * &#64;params undetermined 未确定
         * &#64;params authorized 授权
         */
        const str = `android.permission.${permissionID}` as PlusNavigatorPermissionNames
        const checkPermission = plus.navigator.checkPermission(str)
        if (checkPermission === 'authorized')
          return resolve(true)
        // 判断是否自己在list里面配置了这个权限
        const index = tips.value.findIndex(item => item.name === permissionID)
        console.log(index)

        if (index === -1)
          throw new Error('这个权限没有配置')
        // 唤起原生权限说明弹框
        requstPermissionDialog(index)
        // 授权检测回调
        plus.android.requestPermissions(
          [
            `android.permission.${permissionID}`, // 单个权限
          ],
          (resultObj) => {
            // 权限申请结果
            /**
             * &#64;description resultObj.deniedAlways 永久拒绝授权
             * 多个权限返回结果可能是{'granted':['android.permission.CAMERA'],'deniedPresent':[],'deniedAlways':['android.permission.READ_EXTERNAL_STORAGE']}
             * 这个情况就是我同时授权相册和相机&#xff0c;但是只允许了相机&#xff0c;没有授权相册
             * 这个时候 可以通过deniedAlways 查看哪个权限被永久拒绝了&#xff0c;然后自行在设置弹框内容
             * 所以可以自己判断细分一下&#xff0c;我下面的代码是先判断了是否有永久拒绝的权限&#xff0c;然后直接弹框提示用户去设置
             */
            if (resultObj.deniedAlways && resultObj.deniedAlways.length > 0) {
              uni.showModal({
                title: '提示',
                content: '操作权限已被拒绝，请手动前往设置',
                confirmText: '立即设置',
                success: (res) => {
                  if (res.confirm)
                    gotoAppPermissionSetting()
                  else
                    resolve(false)
                },
              })
              console.log('永久拒绝授权')
            }
            else if (resultObj.deniedPresent && resultObj.deniedPresent.length > 0) {
              resolve(false)
              console.log('拒绝授权')
            }
            else
              if (resultObj.granted && resultObj.granted.length > 0) {
                resolve(true)
                console.log('授权成功')
              }
          },
          (error) => {
            console.log('申请权限错误', error)
            reject(error)
          },
        )
      }
      catch (err) {
        console.log('cuowu ', err)
        reject(err)
      }
    })
  }
  // 监听弹框
  function requstPermissionDialog(index) {
    try {
      if (!permissionListener.value) {
        permissionListener.value = uni.createRequestPermissionListener()
      }
      const dialogData = tips.value[index]
      permissionListener.value.onConfirm(() => dialogStyle(dialogData, true))
      permissionListener.value.onComplete(() => dialogStyle({}, false))
    }
    catch (err) {
      console.log('监听弹框错误', err)
    }
  }
  // 弹框样式
  function dialogStyle({ title = '', content = '' }, status) {
    try {
      if (!status) {
        if (dialogView.value) return dialogView.value.close()
      }

      const systemInfo = uni.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight
      const navigationBarHeight = systemInfo.platform === 'android' ? 48 : 44
      const totalHeight = statusBarHeight + navigationBarHeight
      dialogView.value = new plus.nativeObj.View('per-modal', {
        top: '0px',
        left: '0px',
        width: '100%',
        backgroundColor: '#444',
        // opacity: .5;
      })
      dialogView.value.drawRect({
        color: '#fff',
        radius: '5px',
      }, {
        top: `${totalHeight}px`,
        left: '5%',
        width: '90%',
        height: '100px',
      })
      dialogView.value.drawText(title, {
        top: `${totalHeight + 5}px`,
        left: '8%',
        height: '30px',
      }, {
        align: 'left',
        color: '#000',
      })
      dialogView.value.drawText(content, {
        top: `${totalHeight + 35}px`,
        height: '60px',
        left: '8%',
        width: '84%',
      }, {
        whiteSpace: 'normal',
        size: '14px',
        align: 'left',
        color: '#656563',
      })

      dialogView.value.show()
    }
    catch (e) {
      console.log(e, '权限说明弹框样式错误')
    }
  }
  // 跳转到app权限设置页面
  function gotoAppPermissionSetting() {
    if (uni.getSystemInfoSync().platform !== 'android') {
      const plus_ios = plus.ios as any
      const UIApplication = plus_ios.import('UIApplication')
      const application2 = UIApplication.sharedApplication()
      const NSURL2 = plus_ios.import('NSURL')
      // var setting2 = NSURL2.URLWithString('prefs:root=LOCATION_SERVICES');
      const setting2 = NSURL2.URLWithString('app-settings:')
      application2.openURL(setting2)
      plus_ios.deleteObject(setting2)
      plus_ios.deleteObject(NSURL2)
      plus_ios.deleteObject(application2)
    }
    else {
      // console.log(plus.device.vendor);
      const Intent = plus.android.importClass('android.content.Intent') as any
      const Settings = plus.android.importClass('android.provider.Settings') as any
      const Uri = plus.android.importClass('android.net.Uri') as any
      const mainActivity = plus.android.runtimeMainActivity() as any
      const intent = new Intent()
      intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
      const uri = Uri.fromParts('package', mainActivity.getPackageName(), null)
      intent.setData(uri)
      mainActivity.startActivity(intent)
    }
  }

  return { dialogView, permissionListener, tips, requstPermission, requstPermissionDialog, dialogStyle, gotoAppPermissionSetting }
})
